package com.sy.simpleegg.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.RelativeLayout
import androidx.recyclerview.widget.RecyclerView
import com.sy.simpleegg.R
import com.sy.simpleegg.bean.HomeBtnBean
import com.sy.simpleegg.ext.onClick

class HomeBtnAdapter(private val mContext: Context, private var btnList: List<HomeBtnBean>?) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    private val TAG = "HomeBtnAdapter"
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val view =
            LayoutInflater.from(parent.context).inflate(R.layout.item_home_btn, parent, false)
        return HomeBtnHolder(view)
    }

    @SuppressLint("NewApi")
    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val btnBean = btnList!![position]
        val goodHolder = holder as HomeBtnHolder
        goodHolder.btn.text = btnBean.name
        val params = goodHolder.btn.layoutParams as RelativeLayout.LayoutParams
        if (position == 1 || position % 4 == 1 || position % 4 == 2) {
            Log.d(TAG, "中间位置：$position")
            params.setMargins(
                dp2px(mContext, 3f),
                dp2px(mContext, 0f),
                dp2px(mContext, 3f),
                dp2px(mContext, 0f)
            )
        } else if ((position + 1) % 4 == 0) {
            Log.d(TAG, "右边位置：$position")
            params.setMargins(dp2px(mContext, 3f), dp2px(mContext, 0f), 0, dp2px(mContext, 0f))
        } else if (position % 4 == 0) {
            Log.d(TAG, "左边位置：$position")
            params.setMargins(0, dp2px(mContext, 0f), 0, dp2px(mContext, 0f))
        }
        goodHolder.btn.layoutParams = params
        goodHolder.btn.onClick {
            if (mOnClickListener != null) {
                mOnClickListener!!.onClick(btnBean)
            }
        }
    }

    override fun getItemCount(): Int {
        return if (btnList == null) 0 else btnList!!.size
    }

    internal inner class HomeBtnHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var btn: Button

        init {
            btn = itemView.findViewById(R.id.btn_item)
        }
    }

    fun dp2px(context: Context, dpValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (dpValue * scale + 0.5f).toInt()
    }

    fun setData(newList: List<HomeBtnBean>?) {
        btnList = newList
    }

    interface OnItemClickListener {
        fun onClick(homeBtnBean: HomeBtnBean)
    }

    private var mOnClickListener: OnItemClickListener? = null
    fun setOnItemClickListener(onItemClickListener: OnItemClickListener?) {
        mOnClickListener = onItemClickListener
    }
}
